package com.real8.plusplayground.client.activity;

import com.google.api.gwt.services.plus.shared.Plus;
import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.real8.plusplayground.client.ClientFactory;

public class ActivityReadActivity extends AbstractActivity implements
		ActivityReadView.Presenter {
	private final ClientFactory clientFactory;
	private ActivityReadView view;

	private final ActivityReadPlace place;

	public ActivityReadActivity(ClientFactory clientFactory,
			ActivityReadPlace place) {
		this.clientFactory = clientFactory;
		this.place = place;
	}

	@Override
	public void start(final AcceptsOneWidget panel, EventBus eventBus) {
		// initialize view
		view = clientFactory.getActivityReadView();
		view.setPresenter(this);

		// set id
		view.setId(place.getActivityId());

		getAndSetActivity(place.getActivityId());

		// set view as panel widget
		panel.setWidget(view.asWidget());
	}

	private void getAndSetActivity(final String activityId) {
		// check for plus
		Plus plus = clientFactory.getPlus();
		if (plus != null) {
			plus.activities()
					.get(activityId)
					.to(new Receiver<com.google.api.gwt.services.plus.shared.model.Activity>() {
						@Override
						public void onSuccess(
								com.google.api.gwt.services.plus.shared.model.Activity activity) {
							// push Activity into editor
							view.getEditorDriver().edit(activity);

							// log
							println("Shown: Activity with id="
									+ activity.getId());
						}
					}).fire();
		} else {
			println("Warning: Plus RequestFactory not (yet) initialized");
		}
	}

	private void println(String value) {
		clientFactory.getShell().println(value);
	}

	@Override
	public void onIdChange(String activityId) {
		clientFactory.getPlaceController().goTo(
				new ActivityReadPlace(activityId));
	}
}
